const axios = require('axios');
const { appid, secret } = require('../config/index')['miniProGram'];
const UserModels = require('../models/user');
const { createHoursToken } = require('../utils/jwt');

const showIndex = async (ctx, next) => {
    await ctx.render('index', {
        data: 'user',
    })
}
const wxLogin = async (code) => {
    return axios.get('https://api.weixin.qq.com/sns/jscode2session', {
        params: {
            appid,
            secret,
            js_code: code,
            grant_type: 'authorization_code'
        }
    }).then(res => {
        if (res.data.errcode) return false;
        return res.data;
    });
}
const login = async (ctx, next) => {
    let code = ctx.request.body.code;

    const result = await wxLogin(code);
    if (!result) {
        ctx.body = {
            code: false,
            msg: '登录失败，请重试'
        }
        return;
    }

    // 生成 token
    let token = await createHoursToken(code, result.openid, result.session_key);

    ctx.body = {
        code: true,
        msg: token
    }
}

const getUserInfo = async (ctx, next) => {
    let { token } = ctx.request.query;
    let { openid } = ctx;

    let user = UserModels.findUserByOpenid(openid);

    ctx.body = {
        code: true,
        data: user
    }
}

module.exports = {
    showIndex,
    login,
    getUserInfo
}